package com.sf.rbac.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.sf.rbac.cons.RedisConst;
import com.sf.rbac.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckloginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         response.setContentType("application/json;charset=utf8");
            //获取请求头中的userId
            String userId = request.getHeader("userId");
            //判断userId 是否为空
            if (!StringUtils.isEmpty(userId)) {
                //拼接用户信息key 从redis 删除
                String key = RedisConst.EMPLOYEE_INFO_PREFIX + userId;
                String objJson = redisTemplate.opsForValue().get(key);
                //3 判断redis 中的数据是否为空
                if (StringUtils.isEmpty(objJson)) {
                    //4 如果为空返回401 ,认证失败 ，fail ,null
                    response.getWriter().write(JSON.toJSONString(new JsonResult(401, "认证失败", "fail", null)));
                    return false;
                }
                return true;
                //5 如果不为空 放行
            } else {
                //4 如果为空返回401 ,认证失败 ，fail ,null
                response.getWriter().write(JSON.toJSONString(new JsonResult(401, "认证失败", "fail", null)));
                return false;
            }

        }
    }

